<?php

namespace App\Admin\Forms\Catesets;

use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Models\App;
use App\Models\Cate;

class Setbase extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '设置';

    public function handle(Request $request)
    {
		$id = $request->get('id');
		if( empty($id)){
			admin_error('Error','缺少参数');
			return back();
		}

		$rs = Cate::find($id);
		
		if(empty($rs)){
			admin_error('Error','指定记录不存在');
			return back();
		}		
		$url = $_SERVER['HTTP_REFERER'];
		$arr = parse_url($url);
	
		if(!empty($arr['query'])){
			parse_str($arr['query'],$query_arr);
			$active = $query_arr['active'] ?? 'base';
		}else{
			$active = 'base';
		}
		
		if(request('_restor_with_app')=='on'){
			$sets = $rs->sets;
			unset($sets[$active]);
			$rs->sets = $sets;				
			$rs->save();
			
			admin_success('恢复设置完成');
			return redirect($_SERVER['HTTP_REFERER']);			
		}
		$parameters = $request->except(['_token','_pjax','id','active','_restor_with_app']);
		
		$prepared=[];
        foreach ($this->fields() as $field) {
            $columns = $field->column();

            // If column not in input array data, then continue.
            if (!Arr::has($parameters, $columns)) {
                continue;
            }

			$value = Arr::get($parameters, $columns);

            $value = $field->prepare($value);

            if (is_array($columns)) {
                foreach ($columns as $name => $column) {
                    Arr::set($prepared, $column, $value[$name]);
                }
            } elseif (is_string($columns)) {
                Arr::set($prepared, $columns, $value);
            }
        }

		
		$sets = $rs->sets;
		$sets[$active] = $prepared;
		
		$rs->sets = $sets;
		
		$rs->save();
        admin_success('设置完成');
		return redirect($_SERVER['HTTP_REFERER']);
    }
 
    /**
     * data init.
     */
    public function data()
    {
        $id=(int)request('id');
		$app = get_app_cate(false,$id);
		if(empty($app)){
			admin_error('Error','指定记录不存在');
			return back();		
		}
		$active = request('active','base');
		$app_sets = $app['sets'] ?? [];
		$data = $app_sets[$active] ?? [];

		$data['id'] = $id;
		//dump($data);
		return $data;
    }

	public function reset_app(){
        $id=(int)request('id');
		$cate = get_cate($id);
		$app = get_app_cate($cate['app_name'],$cate);
		if(empty($app)){
			admin_error('Error','指定记录不存在');
			return back();		
		}
		$active = request('active','base');
		$app_sets = $app['sets'] ?? [];
		
		if(!empty($cate['sets'][$active]) && $active !='base'){
			$this->divider();
			$this->switch('_restor_with_app','恢复设置')->help('当前已使用自定义设置,开启并提交将恢复到应用设置或默认的设置');
		}
	}
}
